package com.zigong.app.ui.fragment;

import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsoluteLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.gridsum.tracker.GridsumWebDissector;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.ruihang.generalibrary.ui.dialog.BaseDialogFragment;
import com.ruihang.generalibrary.ui.util.OnItemInternalClick;
import com.ruihang.generalibrary.ui.widget.CustomLinearLayout;
import com.ruihang.generalibrary.utils.ListUtils;
import com.ruihang.generalibrary.utils.NetModeUtil;
import com.ruihang.generalibrary.utils.UrlUtils;
import com.zigong.app.R;
import com.zigong.app.application.Cache;
import com.zigong.app.application.Constances;
import com.zigong.app.application.SiChuanFocusApplication;
import com.zigong.app.beans.AnchorList;
import com.zigong.app.beans.AnchorRecommendItem;
import com.zigong.app.beans.DoUpEvent;
import com.zigong.app.beans.FRebellion;
import com.zigong.app.beans.FUsers;
import com.zigong.app.beans.SingleResult;
import com.zigong.app.http.AbsListNetCallback;
import com.zigong.app.http.AbsNetCallBack;
import com.zigong.app.http.NetUtils;
import com.zigong.app.http.ParamsEditor;
import com.zigong.app.ui.activities.BaoCommentDetailActivity;
import com.zigong.app.ui.activities.ChooseCityActivity;
import com.zigong.app.ui.activities.LoginActivity;
import com.zigong.app.ui.activities.NewesDetailActivity;
import com.zigong.app.ui.activities.RebllionCommitActivity;
import com.zigong.app.ui.adapter.RebllionAdapter;
import com.zigong.app.ui.adapter.holder.RebllionPicHolder;
import com.zigong.app.ui.adapter.holder.VideoPlayHolder;
import com.zigong.app.ui.dialog.ConfirmFragment;
import com.zigong.app.ui.dialog.PicChoiceDiaFragment;
import com.zigong.app.ui.dialog.ShotChoiceDiaFragment;
import com.zigong.app.ui.dialog.ShowDiaFragment;
import com.zigong.app.ui.util.RBaseItemDecoration;
import com.zigong.app.ui.utils.GSFPlayerScreenControllImp;
import com.zigong.app.ui.utils.PictureUtils;
import com.zigong.app.ui.utils.SkipUtil;
import com.zigong.app.utils.UserManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import antlr.debug.MessageEvent;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.app.Activity.RESULT_OK;
import static com.zigong.app.base.BaseActivity.DO_UP_POS;

/**
 * Created by Administrator on 2017/9/4 0004.
 * 报料列表页
 */
public class RebllionFragment extends ColumnBaseFragment implements CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener
        , CanRefreshLayout.IScrollView {
    @BindView(R.id.title_top_logo)
    protected ImageView homeLog;
    @BindView(R.id.rebllion_refresh)
    protected CanRefreshLayout refreshLayout;
    @BindView(R.id.can_content_view)
    protected CustomLinearLayout detail;
    @BindView(R.id.rebllion_list)
    protected RecyclerView rebllion_list;
    @BindView(R.id.video_container)
    protected AbsoluteLayout videoContainer;
    @BindView(R.id.rebllion_top_lay)
    protected LinearLayout title_lay;
    @BindView(R.id.title_top_back)
    protected ImageView backImg;
    private RebllionAdapter mAdapter;
    private boolean mIsLoading = false;
    private int mPageNo = 0;
    private int mPageAll = 0;
    private final static int pageSize = 10;
    private PicChoiceDiaFragment picChoiceDiaFragment;
    private ShotChoiceDiaFragment shotChoiceDiaFragment;
    public static final String PIC_TAG = "dia_pic_choice_fragment";
    public static final String SHOT_TAG = "dia_shot_choice_fragment";
    public static final String REPORT_TAG = "report_fragment";

    private int themeId;
    private List<LocalMedia> selectList = new ArrayList<>();
    public static final String EX_TYPE = "ex_type";
    private int type = -1;//-1代表直接跳转爆料提交,1代表选择图片后提交爆料
    private Handler mHandler;
    private GSFPlayerScreenControllImp screenController;
    protected static final int CODE_REQUEST_LOGIN = 303;
    private RecyclerView.OnScrollListener scrollListener;

    private int height;
    private int dataVersion;
    private ConfirmFragment confirmFragment;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_rebllion, container, false);
        ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        Cache.getInstance().setCurrentChannelId(Cache.getInstance().getCurrentColumnId("报料", "投稿"));
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        backImg.setVisibility(View.GONE);
        themeId = R.style.picture_default_style;
        mHandler = new Handler();
//        scrollListener = new RecyclerView.OnScrollListener() {
//            @Override
//            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
//                super.onScrolled(recyclerView, dx, dy);
//            }
//        };
//        rebllion_list.addOnScrollListener(scrollListener);
        homeLog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), ChooseCityActivity.class);
                startActivity(intent);
            }
        });
        initView();

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        Log.e("sakura", "hidden=" + hidden);
        if (!hidden) {
            Cache.getInstance().setCurrentChannelId(Cache.getInstance().getCurrentColumnId("报料", "投稿"));
            if (null != mAdapter && mAdapter.getItemCount() == 0) {
                onRefresh();
            }
        } else {

        }
    }

    @Override
    public void onDestroyView() {
        if (floatVideoUtils != null) {
            rebllion_list.removeOnScrollListener(floatVideoUtils.getRecyclerScrollListener());
        }
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handlerDoup(DoUpEvent messageEvent) {

        if (null != messageEvent && messageEvent.getPosition() > -1) {
            mAdapter.getItem(messageEvent.getPosition()).setIsDigg(messageEvent.isDigg());
            mAdapter.getItem(messageEvent.getPosition()).setCountDigg(messageEvent.getCountDigg());
            mAdapter.notifyItemChanged(messageEvent.getPosition());
        }

    }


    @Override
    public boolean hasShowPlayer() {
        return floatVideoUtils != null && floatVideoUtils.isHasInited();
    }

    private void initView() {
        final int pa = getResources().getDimensionPixelOffset(R.dimen.divider_shadow_margin_bottom);
        title_lay.postDelayed(new Runnable() {
            @Override
            public void run() {
                height = title_lay.getHeight() + pa;
            }
        }, 300);
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);
        refreshLayout.setLoadMoreEnabled(false);
        rebllion_list.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
        rebllion_list.setItemAnimator(new DefaultItemAnimator());
//        rebllion_list.addItemDecoration(new RBaseItemDecoration(2));
        detail.setiScrollView(this);
        refreshLayout.autoRefresh();
    }

    @Override
    public void onLoadMore() {
        getData();
    }

    @Override
    public void onRefresh() {
        if (mIsLoading) {
            return;
        }
        mPageNo = 0;
        mIsLoading = true;
        getData();
    }

    private void getData() {
        HashMap<String, Object> param = new HashMap<>();
        param.put("page", mPageNo);
        param.put("size", pageSize);
        FUsers user = UserManager.getInstance().getUser();
        if (user != null && !TextUtils.isEmpty(user.getUserId())) {
            param.put("userId", user.getUserId());
        } else {
            param.put("userId", "");
        }

        NetUtils.getNetAdapter().getTopiciscloseList(getOwnerName(), param, new AbsListNetCallback<FRebellion>(FRebellion.class) {
            @Override
            public void onSuc(List<FRebellion> fRebellions) {
                if (fRebellions == null || fRebellions.size() == 0) {
//                    onError(null, null);
                    initData(null);
                    return;
                }

                if (mPageAll == 0) {
                    mPageAll = getPageResponse().getData().getPageAll();
                }
                initData(fRebellions);
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                toast(R.string.loading_no_data);
            }

            @Override
            public void onEnd() {
                onNetFinish();
            }
        });
    }

    private void initData(List<FRebellion> fRebellions) {
        if (fRebellions == null || fRebellions.size() == 0) {
            fRebellions = new ArrayList<>();
        }
//        if (ListUtils.isListValued(fRebellions)){
//            fRebellions.get(0).getDiscloseImage().get(0).setImageUrl("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1507787519984&di=5ac3e6dcde804a18ac62ff69f562d7ff&imgtype=0&src=http%3A%2F%2Fa.hiphotos.baidu.com%2Fzhidao%2Fpic%2Fitem%2F0823dd54564e9258b9b28bca9882d158ccbf4e0b.jpg");
//        }
        if (mAdapter == null) {
            mAdapter = new RebllionAdapter(getContext(), fRebellions).setItemInternalClick(itemClick);
            //    mAdapter.setCommentClick(commentClick);
            rebllion_list.setAdapter(mAdapter);
        }
        if (mPageNo == 0) {
            mAdapter.setData(fRebellions);
        } else {
            mAdapter.addDatas(fRebellions);
        }
        mPageNo++;
    }

    private synchronized void onNetFinish() {
        mIsLoading = false;
        refreshLayout.refreshComplete();
        refreshLayout.loadMoreComplete();
        refreshLayout.setLoadMoreEnabled(mPageNo >= mPageAll ? false : true);
    }

    @OnClick({R.id.rebllion_content_cv, R.id.rebllion_content_iv})
    public void rebllionClick(View view) {
        ArrayList<Pair<String, String>> pairs = new ArrayList<>();
        pairs.add(new Pair<>("页面", "投稿"));
        switch (view.getId()) {
            case R.id.rebllion_content_cv:

                pairs.add(new Pair<>("行为类型", "点击"));
                GridsumWebDissector.getInstance().trackEvent(this, "", "投稿", "", 200, pairs);
                if (!UserManager.isLoginS()) {
                    //toast(R.string.user_info_error_info);
                    toLogin();
                    return;
                }

                Intent intent = new Intent(getContext(), RebllionCommitActivity.class);
                type = -1;
                intent.putExtra(EX_TYPE, type);
                startActivity(intent);
                break;
            case R.id.rebllion_content_iv:
                pairs.add(new Pair<>("行为类型", "点击"));
                GridsumWebDissector.getInstance().trackEvent(this, "", "投稿", "", 200, pairs);
                if (!UserManager.isLoginS()) {
                    toLogin();
                    return;
                }
                if (picChoiceDiaFragment == null) {
                    picChoiceDiaFragment = new PicChoiceDiaFragment();
                }
                picChoiceDiaFragment.setCallBack(picCallBack);
                picChoiceDiaFragment.show(getChildFragmentManager(), PIC_TAG);
                break;
        }
    }


    protected void toLogin() {
        Intent intent = new Intent(getContext(), LoginActivity.class);
        startActivityForResult(intent, CODE_REQUEST_LOGIN);
    }

    OnItemInternalClick itemClick = new OnItemInternalClick() {
        @Override
        public void onItemInternalClick(View itemView, View view, int position) {
            switch (view.getId()) {
                case R.id.item_rebllion_video_play:
                    itemPlayClick(itemView, view, position);
                    break;
                case R.id.li_doup:
                    if (!UserManager.isLoginS()) {
                        toLogin();
                        return;
                    }

                    doUp(mAdapter.getItem(position), position);
                    break;
                case R.id.tv_anchor_comment:
                    if (!UserManager.isLoginS()) {
                        toLogin();
                        return;
                    }
                    Intent intent = new Intent(getActivity(), BaoCommentDetailActivity.class);
                    intent.putExtra(EX_DATA, mAdapter.getItem(position));
                    intent.putExtra(EX_COMMENT_TYPE, 4);
                    intent.putExtra(DO_UP_POS, position);
                    startActivity(intent);
                    break;
                case R.id.tv_report:
                    if (!UserManager.isLoginS()) {
                        toLogin();
                        return;
                    }
                    showConfirm(position);
                    break;

            }
        }
    };

    private void itemPlayClick(View itemView, View view, int position) {
        FRebellion fRebellion = mAdapter.getItem(position);
        if (fRebellion != null) {
            SkipUtil.skipToVideoPlayWithCover(this, UrlUtils.linkUrls(Constances.ST_BASE_URL, fRebellion.getDiscloseVideo())
                    , fRebellion.getPlayedPos(), position,fRebellion.getCoverImage());
        }

    }

    private void doReport(int position){
        SkipUtil.skipToAddUserOperate(getActivity(), getOwnerName(), 17, 3, "投稿举报", mAdapter.getItem(position).getInfoId(), Cache.getInstance().getCurrentChannelId());
    }


    private RebllionPicHolder lastHolder = null;

    private void doUp(final FRebellion aDynamicsItem, final int position) {
        ParamsEditor pe = new ParamsEditor();
        pe.put("dynamicId", aDynamicsItem.getInfoId());
        pe.put("userId", UserManager.getInstance().getUser().getUserId());
        pe.put("fType", 2);

        RecyclerView.LayoutManager manager = rebllion_list.getLayoutManager();
        View lastView = manager.findViewByPosition(position);

        if (null != lastView) {
            lastHolder = (RebllionPicHolder) rebllion_list.getChildViewHolder(lastView);
            if (null != lastHolder) {
                lastHolder.tv_anchor_up.setDrawableEnlarge();

            }
        }


        NetUtils.getNetAdapter().doUpForDynamics(getOwnerName(), pe.getEncryptedParams(UserManager.getInstance().getToken()), new AbsNetCallBack<SingleResult>(SingleResult.class) {
            @Override
            public void onSuc(SingleResult singleResult) {
                if (singleResult.isSuccess()) {

                    RecyclerView.LayoutManager manager = rebllion_list.getLayoutManager();
                    View lastView = manager.findViewByPosition(position);

                    RebllionPicHolder lastHolder = null;
                    if (null != lastView) {
                        lastHolder = (RebllionPicHolder) rebllion_list.getChildViewHolder(lastView);
                        if (mAdapter.getItem(position).getIsDigg()) {
                            mAdapter.getItem(position).setIsDigg(false);
                            mAdapter.getItem(position).setCountDigg(mAdapter.getItem(position).getCountDigg() - 1);

                            Drawable drawable = getResources().getDrawable(R.mipmap.icon_compere_btn_normal);
                            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                            lastHolder.tv_anchor_up.setDrawables(drawable, null, null, null);
                            lastHolder.tv_anchor_up.setTextColor(getResources().getColor(R.color.colorOpinionSelectNo));


                        } else {
                            mAdapter.getItem(position).setIsDigg(true);
                            mAdapter.getItem(position).setCountDigg(mAdapter.getItem(position).getCountDigg() + 1);
                            Drawable drawable = getResources().getDrawable(R.mipmap.icon_compere_btn_press);
                            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                            lastHolder.tv_anchor_up.setDrawables(drawable, null, null, null);
                            lastHolder.tv_anchor_up.setTextColor(getResources().getColor(R.color.color_doup));
                            addInvitation(Constances.ADD_INTEGRAL_DOUP);
                        }

                        int upCount = mAdapter.getItem(position).getCountDigg();
                        if (upCount > 0) {
                            lastHolder.tv_anchor_up.setText(String.valueOf(upCount));
                        } else {
                            lastHolder.tv_anchor_up.setText("点赞");
                        }
                    }
                    //        mAdapter.notifyItemChanged(position);

                    SkipUtil.skipToAddUserOperate(getActivity(), getOwnerName(), 13, 3, "投稿点赞", aDynamicsItem.getInfoId(), Cache.getInstance().getCurrentChannelId());


                }
            }
        });
    }


    private void getShotDiaFragment() {
        if (shotChoiceDiaFragment == null) {
            shotChoiceDiaFragment = new ShotChoiceDiaFragment();
        }
        shotChoiceDiaFragment.setCallBack(shotCallBack);
        shotChoiceDiaFragment.show(getChildFragmentManager(), SHOT_TAG);
    }

    BaseDialogFragment.ICallBack picCallBack = new BaseDialogFragment.ICallBack() {
        @Override
        public void onCallBackMsg(BaseDialogFragment fragment, Message msg) {
            if (msg.what == 1) {
                getShotDiaFragment();
            } else if (msg.what == 2) {
                PictureUtils.choicePic(RebllionFragment.this, themeId, null);
            }
        }
    };
    BaseDialogFragment.ICallBack shotCallBack = new BaseDialogFragment.ICallBack() {
        @Override
        public void onCallBackMsg(BaseDialogFragment fragment, Message msg) {
            if (msg.what == 1) {
                PictureUtils.choicePhoto(RebllionFragment.this);
            } else if (msg.what == 2) {
                PictureUtils.choiceVideo(RebllionFragment.this);
            }
        }
    };

    private void playVideo(View topImg, String url, String title) {
        if (TextUtils.isEmpty(url)) {
            toast(R.string.loading_invalid_data);
            return;
        }
        int netType = NetModeUtil.GetNetype(getContext());
        if (initFloat(topImg, videoContainer, height)) {
//            bottomController.initInfo(liveInfo);
            rebllion_list.addOnScrollListener(floatVideoUtils.getRecyclerScrollListener());
        }
        floatVideoUtils.play(topImg, url, title, true);
    }

    @Override
    public boolean onBackPressed() {
        if (floatVideoUtils != null && floatVideoUtils.onBackPress()) {
            actionToPortrait();
            return true;
        }
        return false;
    }

    @Override
    protected void onChangedToLandscape(Configuration newConfig) {
        super.onChangedToLandscape(newConfig);
//        if (title_lay != null) {
//            title_lay.setVisibility(View.GONE);
//        }
    }

    @Override
    protected void onChangedToPortrait(Configuration newConfig) {
        super.onChangedToPortrait(newConfig);
//        if (title_lay != null) {
//            title_lay.setVisibility(View.VISIBLE);
//        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // if (resultCode == RESULT_OK) {
        switch (requestCode) {
            case PictureConfig.CHOOSE_REQUEST:
                selectList = PictureSelector.obtainMultipleResult(data);
                if (ListUtils.isListValued(selectList)) {
                    Intent intent = new Intent(getContext(), RebllionCommitActivity.class);
                    type = 1;
                    intent.putExtra(EX_TYPE, type);
                    intent.putExtra(EX_DATA, (Serializable) selectList);
                    startActivity(intent);
                }
                break;
            case SkipUtil.REQUEST_CODE_PLAY_BASE:
                playResult(resultCode, data);
                break;
        }
        // }
    }

    @Override
    public boolean canScrollUp(MotionEvent motionEvent) {
        return ViewCompat.canScrollVertically(rebllion_list, -1);
    }

    @Override
    public boolean canScrollDown(MotionEvent motionEvent) {
        return ViewCompat.canScrollVertically(rebllion_list, 1);
    }

    private void playResult(int resultCode, Intent intent) {
        if (intent == null || refreshLayout.isRefreshing()) {
            return;
        }
        int itemPos = intent.getIntExtra(SkipUtil.EX_POS_ITEM, -1);
        if (itemPos >= 0 && mAdapter != null) {
            FRebellion fr = mAdapter.getItem(itemPos);
            if (fr != null) {
                if (resultCode == RESULT_OK) {
                    fr.setPlayedPos(0);
                } else {
                    int pos = intent.getIntExtra(SkipUtil.EX_POS, -1);
                    if (pos > 0) {
                        fr.setPlayedPos(pos);
                    }
                }
            }
        }
    }


    private void showConfirm(int position) {
        if (confirmFragment == null) {
            confirmFragment = new ConfirmFragment();
        }
        confirmFragment.setCallBack(callBack);
        confirmFragment.setPosition(position);
        confirmFragment.show(getActivity().getSupportFragmentManager(), REPORT_TAG);
    }

    //Dialog点击回调
    public BaseDialogFragment.ICallBack callBack = new BaseDialogFragment.ICallBack() {
        @Override
        public void onCallBackMsg(BaseDialogFragment fragment, Message msg) {
            doReport(msg.what);
        }
    };


}
